<script setup>
  import config from './config'
  import { getToken } from '@/utils/auth'
  import { useConfigStore } from '@/store'
  import { getCurrentInstance } from "vue"
  import { onLaunch, onShow } from '@dcloudio/uni-app'

  const { proxy } = getCurrentInstance()

  onLaunch(() => {
    initApp()
  })
  onShow(() => {
    // H5直接地址访问的二次校验
    // #ifdef H5
    checkLogin()
    // #endif
  })

  // 初始化应用
  function initApp() {
    // 初始化应用配置
    initConfig()
    // 检查用户登录状态
    //#ifdef H5
    checkLogin()
    //#endif
  }

  function initConfig() {
    useConfigStore().setConfig(config)
  }

  function checkLogin() {
    const token = getToken()
    // 与全局 permission.js 保持一致的白名单
  const loginPage = '/pages/pc/login'
  const loginAliases = [loginPage, '/login']
  const whiteList = [...loginAliases, '/pages/pc/register', '/pages/pc/passwordForgot', '/pages/common/webview/index']
    // 解析当前路径（history 模式）
    let currentPath = '/'
    if (typeof window !== 'undefined') {
      try {
        const pathname = window.location.pathname || '/'
        currentPath = pathname.replace(/\/+/g, '/').split('?')[0] || '/'
      } catch(e) { currentPath = '/' }
    }

  const normPath = currentPath === '/login' ? loginPage : currentPath
  const inWhite = whiteList.includes(normPath)

    if (!token) {
      if (!inWhite) {
        // 未登录且非白名单，强制跳转登录
        uni.reLaunch({ url: loginPage })
      }
    } else {
      // 已登录时避免停留在登录页
  if (loginAliases.includes(normPath)) uni.reLaunch({ url: '/pages/pc/index' })
    }
  }
</script>

<style lang="scss">
  @import '@/static/scss/index.scss'
</style>
